package com.google.bitcoin.examples;

import com.google.bitcoin.core.AddressFormatException;
import com.google.bitcoin.core.DumpedPrivateKey;
import com.google.bitcoin.core.ECKey;
import com.google.bitcoin.core.NetworkParameters;
import com.google.common.base.Charsets;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @author apetersson
 */
public class ArmoryImporter {

    public static final String PREFIX = "   PrivBase58:";
    private final NetworkParameters network;

    public ArmoryImporter(NetworkParameters network) {
        this.network = network;
    }

    public ImmutableList<ECKey> importFile(String path) {
        try {
            InputStream inputStream = getClass().getResourceAsStream(path);
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, Charsets.UTF_8));
            String line;
            String lastLine = "";
            ImmutableList.Builder<ECKey> builder = ImmutableList.builder();
            while ((line = reader.readLine()) != null) {
                if (line.startsWith(PREFIX)) {
                    ECKey key = new DumpedPrivateKey(network, line.substring(PREFIX.length()).replace(" ", "")).getKey();
                    builder.add(key);
                    String addr = key.toAddress(network).toString();
                    Preconditions.checkState(addr.equals(lastLine), "address did not match. expected: " + lastLine + " but got " + addr);
                }
                lastLine = line;
            }
            return builder.build();
        } catch (AddressFormatException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
